package com.zenithmind.user.service.impl;

import com.zenithmind.user.pojo.domain.User;
import com.zenithmind.user.pojo.vo.UserVO;
import com.zenithmind.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * OAuth2用户信息服务
 * 为OIDC协议提供用户信息
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OAuth2UserInfoService {

    private final UserService userService;

    /**
     * 获取用户信息，用于构建OIDC UserInfo响应
     */
    public OidcUserInfo loadUser(String username) {
        try {
            User user = userService.getUserByUsername(username);
            if (user == null) {
                return new OidcUserInfo(Map.of());
            }

            UserVO userVO = userService.getUserById(user.getId());
            return createOidcUserInfo(userVO);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return new OidcUserInfo(Map.of());
        }
    }

    /**
     * 从用户详情构建OIDC用户信息
     */
    public OidcUserInfo createOidcUserInfo(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        
        // 基本信息
        claims.put("sub", userDetails.getUsername());
        claims.put("preferred_username", userDetails.getUsername());
        
        // 权限信息
        String roles = userDetails.getAuthorities().stream()
            .map(GrantedAuthority::getAuthority)
            .collect(Collectors.joining(" "));
        claims.put("authorities", roles);
        
        return new OidcUserInfo(claims);
    }
    
    /**
     * 从UserVO构建OIDC用户信息
     */
    public OidcUserInfo createOidcUserInfo(UserVO userVO) {
        if (userVO == null) {
            return new OidcUserInfo(Map.of());
        }
        
        Map<String, Object> claims = new HashMap<>();
        
        // 标准OIDC声明
        claims.put("sub", userVO.getId());
        claims.put("preferred_username", userVO.getUsername());
        claims.put("email", userVO.getEmail());
        claims.put("email_verified", true);
        claims.put("name", userVO.getNickname() != null ? userVO.getNickname() : userVO.getUsername());
        claims.put("picture", userVO.getAvatar());
        
        // 自定义声明
        claims.put("user_id", userVO.getId());
        if (userVO.getRole() != null) {
            claims.put("authorities", "ROLE_" + userVO.getRole().getRoleCode());
        }
        claims.put("storage_used", userVO.getStorageUsed());
        claims.put("storage_limit", userVO.getStorageLimit());
        
        return new OidcUserInfo(claims);
    }
} 